package com.beidouin.sensortest;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.HardWare.PCF8591;
import com.friendlyarm.AndroidSDK.FileCtlEnum;
import com.friendlyarm.AndroidSDK.HardwareControler;

import static com.HardWare.PCF8591.ADC_Init;

public class LightActivity extends AppCompatActivity implements Runnable{

    TextView light_txv;
    int devFD=-1;
    Handler handler;
    Thread t = new Thread(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_light);

        light_txv= (TextView) findViewById(R.id.light_ad);
        devFD = HardwareControler.open("/dev/i2c-0", FileCtlEnum.O_RDWR);
        PCF8591.ADC_Init(devFD);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0x101) {
                    light_txv.setText(" " + msg.getData().getInt("adc"));
                }
                super.handleMessage(msg);
            }
        };
        t.start();
    }


    @Override
    protected void onDestroy() {

        HardwareControler.close(devFD);
        //将线程销毁掉
        t.interrupt();
        super.onDestroy();
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted())
        {
            Message m=handler.obtainMessage();
            Bundle bundle =new Bundle();
            m.what=0x101;
            int adc;
            adc = PCF8591.readADC_bychannel(devFD);
            bundle.putInt("adc", adc);
            m.setData(bundle);
            handler.sendMessage(m);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
